<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 新增家庭搜索 -->
      <el-form-item label="家庭" prop="familyId" style="width: 200px;">
        <el-select
            v-model="queryParams.familyId"
            placeholder="选择家庭"
            clearable
            @change="handleFamilyFilter"
        >
          <el-option
              v-for="item in familyOptions"
              :key="item.familyId"
              :label="item.familyName"
              :value="item.familyId"
          />
        </el-select>
      </el-form-item>

      <!-- 新增房间搜索 -->
      <el-form-item label="房间" prop="roomId" style="width: 200px;">
        <el-select
            v-model="queryParams.roomId"
            placeholder="先选择家庭"
            clearable
            :disabled="!queryParams.familyId"
            @change="handleRoomFilter"
        >
          <el-option
              v-for="item in filteredSearchRooms"
              :key="item.roomId"
              :label="item.roomName"
              :value="item.roomId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="温度" prop="temperature">
        <el-input
            v-model="queryParams.temperature"
            placeholder="请输入温度"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="湿度" prop="humidity">
        <el-input
            v-model="queryParams.humidity"
            placeholder="请输入湿度"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记录时间" prop="recordTime">
        <el-date-picker clearable
                        v-model="queryParams.recordTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择记录时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['airsystem:temp:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['airsystem:temp:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['airsystem:temp:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tempList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="记录ID" align="center" prop="recordId" />-->
      <el-table-column
          label="序号"
          align="center"
          width="80"
          class-name="serial-number"
      >
        <template #default="scope">
    <span class="serial">
      {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
    </span>
        </template>
      </el-table-column>
      <el-table-column label="家庭名称" align="center">
        <template #default="scope">
          {{ scope.row._familyName }}
        </template>
      </el-table-column>
      <el-table-column label="房间名称" align="center">
        <template #default="scope">
          {{ scope.row._roomName }}
        </template>
      </el-table-column>

<!--      <el-table-column label="设备ID" align="center" prop="deviceId">-->
<!--        <template #default="scope">-->
<!--          设备ID:{{ scope.row.deviceId }} 温湿度传感器-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="温度" align="center" prop="temperature" />
      <el-table-column label="湿度" align="center" prop="humidity" />
      <el-table-column label="记录时间" align="center" prop="recordTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['airsystem:temp:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['airsystem:temp:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改温湿度记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tempRef" :model="form" :rules="rules" label-width="80px">
        <!-- 新增家庭选择 -->
        <el-form-item label="家庭名称" prop="familyId">
          <el-select
              v-model="form.familyId"
              placeholder="请选择家庭"
              clearable
              @change="handleFamilyChange"
          >
            <el-option
                v-for="item in familyOptions"
                :key="item.familyId"
                :label="item.familyName"
                :value="item.familyId"
            />
          </el-select>
        </el-form-item>
        <!-- 新增房间选择 -->
        <el-form-item label="房间名称" prop="roomId">
          <el-select
              v-model="form.roomId"
              placeholder="请先选择家庭"
              clearable
              :disabled="!form.familyId"
              @change="handleRoomChange"
          >
            <el-option
                v-for="item in filteredRooms"
                :key="item.roomId"
                :label="item.roomName"
                :value="item.roomId"
            />
          </el-select>
        </el-form-item>

        <!-- 修改设备选择 -->
        <el-form-item label="设备ID" prop="deviceId">
          <el-select
              v-model="form.deviceId"
              placeholder="请先选择房间"
              clearable
              :disabled="!form.roomId"
          >
<!--                :label="`设备ID:${item.deviceId} (${getDeviceType(item.deviceName)})`"    -->
            <el-option
                v-for="item in filteredDevices"
                :key="item.deviceId"
                :label="`${getDeviceType(item.deviceName)}`"
                :value="item.deviceId"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="温度" prop="temperature">
          <el-input v-model="form.temperature" placeholder="请输入温度" />
        </el-form-item>
        <el-form-item label="湿度" prop="humidity">
          <el-input v-model="form.humidity" placeholder="请输入湿度" />
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable
                          v-model="form.recordTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Temp">
import { listTemp, getTemp, delTemp, addTemp, updateTemp } from "@/api/airsystem/temp";
import { listDevices } from "@/api/airsystem/devices";
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
// 在顶部添加接口引用
import { listRooms } from "@/api/airsystem/rooms";
import { listFamilies } from "@/api/airsystem/families";


const { proxy } = getCurrentInstance();

const tempList = ref([]);
const deviceOptions = ref([]);
const filteredDeviceOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 搜索用房间过滤
const filteredSearchRooms = computed(() => {
  return roomOptions.value.filter(room =>
      room.familyId === queryParams.value.familyId
  );
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    familyId: null,
    roomId: null,
    deviceId: null,
    temperature: null,
    humidity: null,
    recordTime: null
  },
  rules: {
    familyId: [
      { required: true, message: "必须选择家庭", trigger: "change" }
    ],
    roomId: [
      { required: true, message: "必须选择房间", trigger: "change" }
    ],
    deviceId: [
      { required: true, message: "必须选择设备", trigger: "change" }
    ],
    temperature: [
      { required: true, message: "温度不能为空", trigger: "blur" }
    ],
    humidity: [
      { required: true, message: "湿度不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);




// 在setup区域添加响应式数据
const roomOptions = ref([]);
const familyOptions = ref([]);

// 添加分页获取方法
async function getAllRooms() {
  let allRooms = [];
  let pageNum = 1;
  const pageSize = 100;

  try {
    while (true) {
      const response = await listRooms({ pageNum, pageSize });
      if (!response.rows?.length) break;
      allRooms = [...allRooms, ...response.rows];
      if (response.rows.length < pageSize) break;
      pageNum++;
    }
    return allRooms;
  } catch (error) {
    console.error("获取房间失败:", error);
    return [];
  }
}

async function getAllFamilies() {
  let allFamilies = [];
  let pageNum = 1;
  const pageSize = 100;

  try {
    while (true) {
      const response = await listFamilies({ pageNum, pageSize });
      if (!response.rows?.length) break;
      allFamilies = [...allFamilies, ...response.rows];
      if (response.rows.length < pageSize) break;
      pageNum++;
    }
    return allFamilies;
  } catch (error) {
    console.error("获取家庭失败:", error);
    return [];
  }
}


/** 可靠获取所有设备的方法 */
async function getAllDevices() {
  let allDevices = [];
  let pageNum = 1;
  const pageSize = 100; // 每页大小

  try {
    while (true) {
      const response = await listDevices({
        pageNum,
        pageSize
      });
      // 检查返回数据是否有效
      if (!response.rows || response.rows.length === 0) {
        break;
      }
      // 合并数据
      allDevices = [...allDevices, ...response.rows];
      // 判断是否还有更多数据
      if (response.rows.length < pageSize) {
        break;
      }
      pageNum++;
    }
    return allDevices;
  } catch (error) {
    console.error("分页获取设备失败:", error);
    proxy.$modal.msgError("获取设备数据失败");
    return [];
  }
}

/** 查询设备列表并过滤出deviceName="0"的设备 */
async function getDeviceList() {
  loading.value = true;
  try {
    // 获取所有设备
    const allDevices = await getAllDevices();
    // 存储所有设备
    deviceOptions.value = allDevices;
    // 严格筛选温湿度传感器（deviceName="0"）
    filteredDeviceOptions.value = allDevices.filter(
        device => device.deviceName === "0"
    );

    console.log('获取到的设备总数:', allDevices.length);
    console.log('温湿度传感器数量:', filteredDeviceOptions.value.length);

    // 如果没有找到温湿度传感器，显示提示
    if (filteredDeviceOptions.value.length === 0) {
      proxy.$modal.msgWarning("系统中未找到温湿度传感器设备");
    }

  } catch (error) {
    console.error("处理设备数据失败:", error);
    proxy.$modal.msgError("获取设备列表失败");
  } finally {
    loading.value = false;
  }
}


/** 查询温湿度记录列表 */
async function getList() {
  try {
    loading.value = true;
    const response = await listTemp(queryParams.value);
    // 关联数据
    tempList.value = response.rows.filter(record => {
      // 获取关联设备
      const device = deviceOptions.value.find(d => d.deviceId === record.deviceId);
      if (!device) return false;

      // 前端过滤逻辑
      const familyMatch = queryParams.value.familyId
          ? roomOptions.value.find(r => r.roomId === device.roomId)?.familyId === queryParams.value.familyId
          : true;
      // 房间过滤
      const roomMatch = queryParams.value.roomId
          ? device.roomId === queryParams.value.roomId
          : true;

      // 设备过滤
      const deviceMatch = queryParams.value.deviceId
          ? device.deviceId === queryParams.value.deviceId
          : true;

      return familyMatch && roomMatch && deviceMatch;
    })
        .map(record => {
      // 找到设备
      const device = deviceOptions.value.find(d => d.deviceId === record.deviceId);
      // 找到房间
      const room = roomOptions.value.find(r => r.roomId === device?.roomId);
      // 找到家庭
      const family = familyOptions.value.find(f => f.familyId === room?.familyId);
      return {
        ...record,
        _familyName: family?.familyName || '未知家庭',
        _roomName: room?.roomName || '未知房间'
      };
    });
    total.value = tempList.value.length;
  } catch (error) {
    console.error("获取记录失败:", error);
  } finally {
    loading.value = false;
  }
}
const handleFamilyFilter = () => {
  queryParams.value.roomId = null; // 清空已选房间
  queryParams.value.deviceId = null; // 新增重置设备
  handleQuery();
};

// 搜索用设备过滤
const filteredSearchDevices = computed(() => {
  if (!queryParams.value.roomId) return [];
  return deviceOptions.value.filter(device =>
      device.roomId === queryParams.value.roomId &&
      device.deviceName === "0" // 保持温湿度传感器过滤
  );
});


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    deviceId: null,
    temperature: null,
    humidity: null,
    recordTime: null
  };
  proxy.resetForm("tempRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    familyId: null,
    roomId: null,
    deviceId: null,
    temperature: null,
    humidity: null,
    recordTime: null
  };
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加温湿度记录";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  try {
    reset();
    const _recordId = row.recordId || ids.value;
    const response = await getTemp(_recordId);


    // 找到关联设备
    const device = deviceOptions.value.find(d => d.deviceId === response.data.deviceId);
    // 找到房间
    const room = roomOptions.value.find(r => r.roomId === device?.roomId);

    form.value = {
      ...response.data,
      familyId: room?.familyId,
      roomId: device?.roomId
    };
    open.value = true;
    title.value = "修改温湿度记录";
  } catch (error) {
    console.error("获取记录详情失败:", error);
    proxy.$modal.msgError("获取记录详情失败");
  }
}

/** 提交按钮 */
async function submitForm() {
  try {
    const valid = await proxy.$refs["tempRef"].validate();
    if (valid) {
      if (form.value.recordId != null) {
        await updateTemp(form.value);
        proxy.$modal.msgSuccess("修改成功");
      } else {
        await addTemp(form.value);
        proxy.$modal.msgSuccess("新增成功");
      }
      open.value = false;
      getList();
    }
  } catch (error) {
    console.error("提交表单失败:", error);
  }
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    const _recordIds = row.recordId || ids.value;
    await proxy.$modal.confirm(`是否确认删除温湿度记录编号为"${_recordIds}"的数据？`);
    await delTemp(_recordIds);
    getList();
    proxy.$modal.msgSuccess("删除成功");
  } catch (error) {
    console.error("删除记录失败:", error);
  }
}


// 新增计算属性
const filteredRooms = computed(() => {
  return roomOptions.value.filter(room =>
      room.familyId === form.value.familyId
  );
});

const filteredDevices = computed(() => {
  return deviceOptions.value
      .filter(device =>
          device.roomId === form.value.roomId &&
          device.deviceName === "0" // 保持温湿度传感器过滤
      )
      .map(device => ({
        ...device,
        typeLabel: getDeviceType(device.deviceName)
      }));
});

// 设备类型转换方法（假设有字典）
const getDeviceType = (deviceName) => {
  const deviceTypeMap = {
    '0': '温湿度传感器',
    '2': 'PM传感器',
    '4': '甲醛检测传感器'
  };
  return deviceTypeMap[deviceName] || '未知设备';
};

// 事件处理
const handleFamilyChange = () => {
  form.value.roomId = null;
  form.value.deviceId = null;
};

const handleRoomChange = () => {
  form.value.deviceId = null;
};

// 房间选择事件
const handleRoomFilter = () => {
  queryParams.value.deviceId = null; // 重置设备选择
  handleQuery();
};

// 组件挂载时初始化
onMounted(async () => {
  await Promise.all([
    getDeviceList(),
    getAllRooms().then(rooms => roomOptions.value = rooms),
    getAllFamilies().then(families => familyOptions.value = families)
  ]);
  getList();
});
</script>
